<?php

class Memcahe
{
	//private $host = 'localhost';//主机
	private $port = 11211;//端口

	public function __construct()
	{
		$this->conn = mysql_connect($this->host, $this->root, $this->password) or die("Could not connect: " . mysql_error());
		mysql_select_db($this->dbname, $this->conn); 
		mysql_query("set names 'utf8'");

		$this->cache = @memcache_connect($this->host, $this->port);
		if(!$this->cache)
		{
			die('memcache connect fail!');
		}
	}

	public function set($items,$time = 0,$flag = true)//当key存在时 替换原来的value，不存在时 写入value。
	{
		if($items && is_array($items))
		{
			foreach($items as $key => $val)
			{
				memcache_set($this->cache,$key,$val,$flag,$time);
			}

		}else{
			die('保存对象必须为Array类型!');
		}
	}
	
	public function add($items,$time = 0,$flag = true)//当key不存在时 写入value，否则写入失败
	{
		if($items && is_array($items))
		{
			foreach($items as $key => $val)
			{
				memcache_add($this->cache,$key,$val,$flag,$time);
			}

		}else{
			die('保存对象必须为Array类型!');
		}
	}
	
	public function replace($items,$time = 0,$flag = true)//当key存在时 才会写入value，否则写入失败
	{		
		if($items && is_array($items))
		{
			foreach($items as $key => $val)
			{
				memcache_replace($this->cache,$key,$val,$flag,$time);
			}
		}else{
			die('保存对象必须为Array类型!');
		}
	}
	
	public function get($key)
	{
		if(memcache_get($this->cache,$key))
		{
			return memcache_get($this->cache,$key);
		}else{
			return null;
		}
	}

	public function delete($items,$time = 0)
	{
		if($items)
		{
			if(is_array($items))
			{
				foreach($items as $val)
				{
					memcache_delete($val,$time);
				}
				return true;
			}else{
				return memcache_delete($items,$time);
			}

		}else{
			return false;
		}	
	}

	public function __destruct()
	{
		//$this->cache->flush();//刷新
	}
}
?>